<script setup lang="ts">
import { computed, ref } from 'vue'
import { useStorage } from '@vueuse/core'
import { ElMessageBox, ElNotification } from 'element-plus'
import { instance } from '@/utils/request'
import { useLoadingStore } from '@/store/loading'

const { toggleLoading } = useLoadingStore()

const agvStatus = useStorage<any[]>('agv-status', [])

const currentAgvId = ref(1)

const loading = ref(false)

const switchAgv = () => {
  loading.value = true
  currentAgvId.value = currentAgvId.value === 1 ? 2 : 1
  setTimeout(() => (loading.value = false), 1000)
}

const currentAgv = computed(() => {
  return agvStatus.value.find((item) => {
    if (item.id === currentAgvId.value) return item
  })
})

const itemDataA = [
  { prop: 'name', name: 'AGV 名称' },
  { prop: 'status', name: '在线状态' },
  { prop: 'deviceStatus', name: '设备状态' },
  { prop: 'navigationStatus', name: '导航状态' },
  { prop: 'canStatus', name: 'CAN 状态' },
  { prop: 'pass', name: '通行状态' },
  { prop: 'ribbon', name: '色带识别状态' },
  { prop: 'stopStatus', name: '停止状态' },
  { prop: 'power', name: '当前电量' },
  { prop: 'powerStatus', name: '充电状态' },
  { prop: 'orcCode', name: '二维码状态' },
  { prop: 'alignmentStatus', name: '对准状态' },
  { prop: 'loadStatus', name: '料罐状态' },
  { prop: 'barrier', name: '障碍物识别状态' },
  { prop: 'barCode', name: '条形码识别状态' },
  { prop: 'updateTime', name: '最后更新时间' },
]

const itemDataB = [
  { prop: 'electricalStatus1', name: '前轮动力电机' },
  { prop: 'electricalStatus2', name: '前轮转向电机' },
  { prop: 'electricalStatus3', name: '后轮动力电机' },
  { prop: 'electricalStatus4', name: '后轮转向电机' },
  { prop: 'electricalStatus5', name: '顶升动力电机' },
  { prop: 'position', name: '当前点位' },
  { prop: 'lastPosition', name: '前置点位' },
  { prop: 'height', name: '顶升高度' },
  { prop: 'direction', name: '行走方向' },
  { prop: 'visionStatus', name: '视觉避障' },
  { prop: 'voltage', name: '电池电压' },
  { prop: 'temperature1', name: '主电箱温度 A' },
  { prop: 'temperature2', name: '主电箱温度 B' },
  { prop: 'temperature3', name: '电池箱温度' },
  { prop: 'temperature4', name: '副电箱温度' },
]

const getContent = (item, val) => {
  if (item.prop === 'name') {
    // AGV 名称
    return !val ? currentAgv.value?.[item.prop] : 'success'
  } else if (item.prop === 'status') {
    // 在线状态
    const map = {
      '0': ['离线', 'danger'],
      '1': ['离线', 'danger'],
      '2': ['在线', 'success'],
    }
    return map[currentAgv.value?.[item.prop]]?.[val]
  } else if (item.prop === 'deviceStatus') {
    // 设备状态
    const map = { 0: ['正常', 'success'], 1: ['异常', 'danger'] }
    return map[currentAgv.value?.[item.prop]]?.[val]
  } else if (item.prop === 'loadStatus') {
    // 料罐状态
    const map = { 0: ['无料罐', 'info'], 1: ['有料罐', 'warning'] }
    return map[currentAgv.value?.[item.prop]]?.[val]
  } else if (item.prop === 'stopStatus') {
    // 停止状态
    const map = { 0: ['正常', 'success'], 1: ['已停止', 'warning'] }
    return map[currentAgv.value?.[item.prop]]?.[val]
  } else if (item.prop === 'canStatus') {
    // CAN状态
    return currentAgv.value?.[item.prop] === 0
      ? !val
        ? '正常'
        : 'success'
      : !val
        ? '异常'
        : 'danger'
  } else if (item.prop === 'navigationStatus') {
    // 导航状态
    const map = { '0': ['待机', 'warning'], '1': ['导航中', 'success'] }
    return map[currentAgv.value?.[item.prop]]?.[val]
  } else if (item.prop === 'power') {
    // 当前电量
    if (currentAgv.value?.[item.prop] < 0) {
      return 0
    } else if (currentAgv.value?.[item.prop] > 100) {
      return 100
    } else {
      return currentAgv.value?.[item.prop]
    }
  } else if (item.prop === 'powerStatus') {
    // 充电状态
    const map = { 0: ['断开', 'warning'], 1: ['通路', 'success'] }
    return map[currentAgv.value?.[item.prop]]?.[val]
  } else if (item.prop === 'orcCode') {
    // 二维码状态
    const map = { 0: ['无二维码', 'warning'], 1: ['检测到二维码', 'success'] }
    return map[currentAgv.value?.[item.prop]]?.[val]
  } else if (item.prop === 'alignmentStatus') {
    // 对准状态
    const map = { 0: ['无', 'warning'], 1: ['正在对准中', 'success'] }
    return map[currentAgv.value?.[item.prop]]?.[val]
  } else if (String(item.prop).includes('Time')) {
    // 色带脱离时间 and 最后更新时间
    return !val ? currentAgv.value?.[item.prop] : 'success'
  } else if (String(item.prop).includes('electricalStatus')) {
    // 电机状态
    const map = { 0: ['正常', 'success'], 1: ['异常', 'danger'] }
    return map[currentAgv.value?.[item.prop]]?.[val]
  } else if (item.prop === 'position' || item.prop === 'lastPosition') {
    // 点位信息
    return !val ? currentAgv.value?.[item.prop] : 'success'
  } else if (item.prop === 'height') {
    // 顶升高度
    return !val ? currentAgv.value?.[item.prop] + ' mm' : 'success'
  } else if (item.prop === 'direction') {
    // 行走方向
    const map = { 0: ['车尾行进', 'success'], 1: ['车头行进', 'success'] }
    return map[currentAgv.value?.[item.prop]]?.[val]
  } else if (item.prop === 'visionStatus') {
    // 视觉避障
    const map = { 0: ['关闭', 'danger'], 1: ['开启', 'success'] }
    return map[currentAgv.value?.[item.prop]]?.[val]
  } else if (item.prop === 'voltage') {
    // 电池电压
    return !val ? currentAgv.value?.[item.prop] + ' V' : 'success'
  } else if (String(item.prop).includes('temperature')) {
    // 温度相关
    return !val ? currentAgv.value?.[item.prop] + ' °C' : 'success'
  } else if (['barCode', 'ribbon'].includes(item.prop)) {
    // 条形码和色带识别状态
    const map = { 0: ['未识别到', 'warning'], 1: ['已识别到', 'success'] }
    return map[currentAgv.value?.[item.prop]]?.[val]
  } else if (item.prop === 'pass') {
    // 通行状态
    const map = { 0: ['已放行', 'success'], 1: ['等待中', 'warning'] }
    return map[currentAgv.value?.[item.prop]]?.[val]
  } else if (item.prop === 'barrier') {
    // 障碍物识别状态
    const map = { 0: ['无障碍物', 'success'], 1: ['有障碍物', 'warning'] }
    return map[currentAgv.value?.[item.prop]]?.[val]
  } else {
    return !val ? '未知' : 'danger'
  }
}

const remoteControl = async (code) => {
  await ElMessageBox.confirm('请确认是否继续操作', '警告')
  try {
    toggleLoading(true)
    await instance({
      url: `/remote/v1/jacking/control`,
      method: 'get',
      params: { id: currentAgvId.value, code },
    })
    ElNotification({ type: 'success', title: '指令发送成功' })
    toggleLoading(false)
  } catch (error) {
    toggleLoading(false)
  }
}

const realignmentControl = async () => {
  await ElMessageBox.confirm('请确认是否继续操作', '警告')
  try {
    toggleLoading(true)
    await instance({
      url: `/remote/v1/agv/realignment`,
      method: 'get',
      params: { id: currentAgvId.value },
    })
    ElNotification({ type: 'success', title: '指令发送成功' })
    toggleLoading(false)
  } catch (error) {
    toggleLoading(false)
  }
}
</script>

<template>
  <div
    class="common text-#96d8ff flex flex-col gap-4 relative"
    v-loading="loading"
    element-loading-background="rgba(0, 0, 0, 0.2)"
    element-loading-text="等待响应中..."
  >
    <div class="title">AGV 状态</div>
    <div class="absolute top-4 right-4">
      <ADropdown position="br">
        <ElButton color="#4e648763" class="p-2"
          ><i class="i-icons:menu text-16px mb-0.5"
        /></ElButton>
        <template #content>
          <ADoption @click="switchAgv()">切换车辆</ADoption>
          <ADoption @click="realignmentControl()">重新对准</ADoption>
          <ADsubmenu>
            <template #default>顶升控制</template>
            <template #content>
              <ADoption @click="remoteControl(0)">上升</ADoption>
              <ADoption @click="remoteControl(1)">下降</ADoption>
            </template>
          </ADsubmenu>
        </template>
      </ADropdown>
    </div>
    <div
      class="h-56 grid grid-flow-col grid-cols-[120px_240px_1fr] grid-rows-8 [&>div]:self-center gap-2"
    >
      <div class="i-icons:agv-off h-24 w-24 row-span-8 place-self-center"></div>
      <div v-for="item in itemDataA" :key="item.prop" class="flex gap-2">
        <div class="w-28 text-right">{{ item.name }}：</div>
        <ElProgress
          v-if="item.prop === 'power'"
          class="w-34"
          status="success"
          :text-inside="true"
          :stroke-width="24"
          :percentage="getContent(item, 0)"
        />
        <ElTag v-else :type="getContent(item, 1)">{{
          getContent(item, 0)
        }}</ElTag>
      </div>
    </div>
    <div
      class="h-32 grid grid-flow-col grid-cols-3 grid-rows-5 [&>div]:self-center gap-2"
    >
      <div v-for="item in itemDataB" :key="item.prop" class="flex gap-2">
        <div class="w-30 text-right">{{ item.name }}：</div>
        <ElTag :type="getContent(item, 1)">{{ getContent(item, 0) }}</ElTag>
      </div>
    </div>
  </div>
</template>
